<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- 搜索 -->
    <!-- 紧急返件要求下发 -->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="110" @filterChange="changeHandle" @resetChange="resetHandle"></TopFilter>
    <!-- table -->
    <FilterTable ref="table" :columns="columns" :params="fetchParams"  :datakey="'records'" :fetchapi="fetchApi" :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectChange" :isSelectColumn='true' >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary"  :click="exportFileBtn.bind()">导出</multiuse-button>
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="addTurnOn()">新增</multiuse-button>
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="batchDown()">下发</multiuse-button>
      </template>
    </FilterTable>
    <Drawer :visible.sync="visibleDetail" :title="'紧急返件要求下发明细'" destroyOnClose width="70%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <DetailForm @close="closeDetail" @save="saveDetail" :rowData="rowData"></DetailForm>
    </Drawer>
    <Drawer :visible.sync="visibleEdit" :title="'紧急返件要求下发编辑'" destroyOnClose width="70%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditForm @close="closeEdit" @save="saveEdit" :rowData="rowData"></EditForm>
    </Drawer>
    <Drawer :visible.sync="visibleAdd" :title="'紧急返件要求下发新增'" destroyOnClose width="70%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </Drawer>
    <Drawer :visible.sync="visibleEditAf" :title="'紧急返件要求下发编辑'" destroyOnClose width="70%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditFormAf @close="closeEdit" @save="saveEdit" :rowData="rowData"></EditFormAf>
    </Drawer>
    <Drawer :visible.sync="visibleAddAf" :title="'紧急返件要求下发新增'" destroyOnClose width="70%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <AddFormAf @close="closeAdd" @save="saveAdd"></AddFormAf>
    </Drawer>
    <BaseDialog :visible.sync="visible" :title="'车型选择'" destroyOnClose width="850px" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <ModelVehicle @close="close" @save="save"></ModelVehicle>
    </BaseDialog>
    <BaseDialog :visible.sync="selectDelearFlag" :title="dialogTitle" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple"/>
    </BaseDialog>
  </div>
  </Spin>
</template>
<script>
import {
  getListByPage,
  getListForExport,
  deleteOne,
  piliangBack,
  piliangDown,
  exporturl,
  batchUpdateJf, getListForExportNew
} from '@/api/usedPartsReturnManage/usedPartsReturn_OEM/CoreIssueRules/index';
import DetailForm from './DetailForm.vue';
import EditForm from './EditForm.vue';
import AddForm from './AddForm.vue';
import EditFormAf from './EditFormAf.vue';
import AddFormAf from './AddFormAf.vue';
import ModelVehicle from '@/pages/claimDemage/tools/ModelVehicle.vue';
import { exportExcelFile } from '@/utils/index';
import { getPartType } from '@/api/dictionary/index';
import { dictionary } from '@/utils/dictMixin';
import moment from "moment";
import { getAppId } from '@/assets/js/auth';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';

export default {
  mixins: [dictionary],
  components: {
    DetailForm,
    EditForm,
    ModelVehicle,
    AddForm,
    AddFormAf,
    EditFormAf,
    DealerList
  },
  data() {
    return {
      loading: false,
      dataList: [],
      visible: false,
      visibleDrawer: false,
      collapse: true,
      infoId: null,
      topFilterInit: this.topFilterInitFun(),
      flterValue: {}, //参数
      columns: this.creatHeader(),
      fetchApi: getListByPage,
      fetchParams: {
        flag: 2,xhrAbort: true,
        ownerCode: null
      }, //ipa 接口
      selectedRows: [], //选中服务站
      visibleDetail: false,
      visibleEdit: false,
      visibleAdd: false,
      visibleEditAf: false,
      visibleAddAf: false,
      rowData:{},
      selectDelearFlag: false,
      ownerCode: "",
      dealerList: [],
      dealerCompanyCode: [],
      dealerData: [],
      selectDealerData: []
    };
  },
  created() {
    this.fetchParams.beginCreatedAt = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
    this.fetchParams.endCreatedAt = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
    this.chuqi();
  },
  methods: {
    //服务站选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    },
    //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //保存
    Delearsave(val) {
      console.log(val)
      this.dealerData = val;
      this.selectDealerData = [];
      // this.dealer = {...val[0]};
      // this.ownerCode = val[0].dealerCompanyCode;
      let ownerCodeArr = [];
      let dealerNameArr = [];
      val.forEach(item => {
        ownerCodeArr.push(item.dealerCompanyCode);
        this.selectDealerData.push(item.dealerCompanyCode);
        // ownerCodeArr.push(item.dealerCode);
        dealerNameArr.push(item.dealerName);
      });
      // this.topFilterInit.find(x => x.fieldName == 'showOwnerCode').initialValue = dealerNameArr.join(",");
      if (ownerCodeArr.length > 0) {
        this.fetchParams.ownerCode = ownerCodeArr.join(",");
        console.log("ownerCode", this.fetchParams.ownerCode)
      }
      this.selectDelearFlag = false;
    },
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'INPUT', label: '紧急返件单号', fieldName: 'jfNo', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '索赔单号', fieldName: 'cmsClaimNo', placeholder: '请输入', initialValue: '' },
        {
          type: 'SELECT',
          label: '服务站',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
          onChange: val => {
            console.log(val)
          }
        },
        { type: 'INPUT', label: '旧件名称', fieldName: 'partName', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '旧件代码', fieldName: 'partCode', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: 'VIN', fieldName: 'vin', placeholder: '请输入', initialValue: '' },
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'jfStatus',
          placeholder: '请选择单据状态...',
          initialValue: '',
          itemList: []
        },
        { type: 'RANGE_DATE', label: '创建日期', fieldName: 'beginCreatedAt|endCreatedAt', placeholder: '请输入',
          initialValue: [
            moment()
              .startOf('week')
              .format('YYYY-MM-DD HH:mm:ss'),
            moment()
              .endOf('week')
              .format('YYYY-MM-DD HH:mm:ss')
          ],
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
      ];
    },
    //索赔类型下拉框
    async chuqi() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({type: 5565});
      if (res.resultCode == 200) {
        this.topFilterInit.find(x => x.fieldName == 'jfStatus').initialValue = '';
        this.topFilterInit.find(x => x.fieldName == 'jfStatus').itemList = res.data.map(y => ({
          text: y.codeCnDesc,
          value: y.codeId
        }));
      }
    },
    //搜索获取数据
    changeHandle(val) {
      if(!val.beginCreatedAt) {
        this.$notify.warning({ title: '提示信息', message: '创建开始日期不可为空！' });
        return
      }
      if(!val.endCreatedAt) {
        this.$notify.warning({ title: '提示信息', message: '创建结束日期不可为空！' });
        return
      }
      if(getAppId() == 'arcfox') {
        if (moment(moment(val.endCreatedAt).format('YYYY-MM-DD')).diff(moment(val.beginCreatedAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '创建日期跨度不可超过十二个月！' });
          return
        }
      } else {
        if (moment(moment(val.endCreatedAt).format('YYYY-MM-DD')).diff(moment(val.beginCreatedAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '创建日期跨度不可超过十二个月！' });
          return
        }
      }
      if (!this.ownerCode) {
        this.ownerCode = val.showOwnerCode
      }
      if (!val.showOwnerCode) {
        this.ownerCode = null
      }
      this.fetchParams=Object.assign({}, this.fetchParams, val,{
        flag:2,xhrAbort: false
      });
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 130,
          fixed: 'left',
          render: props => {
            return (
              <div style="text-align:center">
                <el-button size="mini" type="text" disabled={props.row.jfStatus == 55651001 ? false : true} onClick={() => this.send(props.row)}>
                  下发
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" disabled={props.row.jfStatus == 55651001 ? false : true}
                           onClick={() => this.del(props.row)}>
                  作废
                </el-button>
              </div>


          );
          }
        },
        {title: '紧急返件单号', dataIndex: 'jfCode', sorter: true},
        {title: '单据状态', dataIndex: 'jfStatusStr', sorter: true},
        {title: '索赔单号', dataIndex: 'cmsClaimNo', sorter: true},
        {title: '索赔单状态', dataIndex: 'cmsReturnStatusStr', sorter: true},
        {title: '服务站代码', dataIndex: 'ownerCode', sorter: true},
        {title: '服务站简称', dataIndex: 'dealerName', sorter: true},
        {title: '旧件代码', dataIndex: 'partCode', sorter: true},
        {title: '旧件名称', dataIndex: 'partName', sorter: true},
        {title: '数量', dataIndex: 'partCount', sorter: true},
        {title: '索赔类型', dataIndex: 'cmsClaimTypeStr', sorter: true},
        {title: 'VIN', dataIndex: 'vin', sorter: true},
        { title: '车型名称', dataIndex: 'vehicleType', sorter: true },
        { title: '收件仓库', dataIndex: 'whName', sorter: true },
        { title: '联系人', dataIndex: 'conPerson', sorter: true },
        { title: '联系电话', dataIndex: 'conTel', sorter: true },
        { title: '邮寄地址', dataIndex: 'conAddress', sorter: true },
        { title: '创建人', dataIndex: 'createdBy', sorter: true },
        { title: '创建时间', dataIndex: 'createdAt', dateFormat: 'YYYY年MM月DD日 HH:mm:ss' },
        { title: '下发人', dataIndex: 'issueBy', sorter: true },
        { title: '下发时间', dataIndex: 'issueAt', sorter: true, dateFormat: 'YYYY年MM月DD日 HH:mm:ss' }
      ];
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    modelTurnOn() {
      this.visible = true;
    },
    addTurnOn() {
      if (getAppId() == 'arcfox') {
        this.visibleAddAf = true;
      }else {
        this.visibleAdd = true;
      }
    },
    // 导出
  async  exportFileBtn() {
      try {
        // let params = { reportNo: "RE202103060001" }
        let params = {...this.fetchParams}
        let res = await getListForExportNew(params);
        exportExcelFile(res.data, '紧急返件列表')
      } catch (err) {
        console.warn(err)
      }
    // getListForExport(this.fetchParams)
      // let json = Object.assign({}, { CODE: 'CODE_00000161' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      // let beginSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[0];
      // let endSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[1];
      // if(!beginSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '创建开始日期不可为空！' });
      //   return
      // }
      // if(!endSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '创建结束日期不可为空！' });
      //   return
      // }
      // if(getAppId() == 'arcfox') {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '创建日期跨度不可超过十二个月！' });
      //     return
      //   }
      // } else {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '创建日期跨度不可超过十二个月！' });
      //     return
      //   }
      // }
      // let obj = Object.assign({}, this.fetchParams ,{ flag:2, xhrAbort: false});
      // obj.beginCreatedAt = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[0];
      // obj.endCreatedAt = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[1];
      // getListForExport(obj).then(res => {
      //   exportExcelFile(res.data, '紧急下发信息');
      // });
    },
    detail(val) {
      this.rowData = val;
      this.visibleDetail = true;
    },
    edit(val) {
      this.rowData = val;
      if (getAppId() == 'arcfox') {
        this.visibleEditAf = true;
      }else {
        this.visibleEdit = true;
      }
    },
    closeDetail() {
      this.visibleDetail = false;
    },
    saveDetail() {
      this.visibleDetail = false;
      this.fetchParams = { ...this.fetchParams };
    },
    closeEdit() {
      this.visibleEdit = false;
      this.visibleEditAf = false;
    },
    saveEdit() {
      this.visibleEdit = false;
      this.visibleEditAf = false;
      this.fetchParams = { ...this.fetchParams };
    },
    closeAdd() {
      this.visibleAdd = false;
      this.visibleAddAf = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.visibleAddAf = false;
      this.fetchParams = { ...this.fetchParams };
    },
    close() {
      this.visible = false;
    },
    save(obj) {
      this.visible = false;
      this.topFilterInit.find(x => x.fieldName == 'modelCode').initialValue = obj[0].address;
      this.fetchParams = { ...this.fetchParams };
    },
    //下发
    async send(data){
        const res = await batchUpdateJf({jfCode: data.jfCode, jfStatus: 55651002});
        if (res.resultCode != 200) {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '下发失败!' });
        } else {
          this.$notify.success({ title: '提示信息', message: '下发成功!' });
          // 重新加载
          this.fetchParams = { ...this.fetchParams };
        }
    },
    //作废
    del(data){
      this.$confirm('确定作废吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await batchUpdateJf({jfCode: data.jfCode, jfStatus: 55651003});
          if (res.resultCode != 200) {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '删除失败!' });
          } else {
            this.$notify.success({ title: '提示信息', message: '删除成功!' });
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
          }
        })

      // let res = [];
      // res = await deleteOne({ ptId: data.ptId });
      // if (res.resultCode == 200) {
      //   this.fetchParams = Object.assign({}, this.fetchParams);
      // } else if (res.resultCode == '403') {
      //   console.info('不能删除:{}', res);
      //   this.$notify.error({
      //     title: '失败',
      //     message: res.errMsg
      //   });
      // }
    },
    //批量下发
    async batchDown() {
      if (this.selectedRows.length > 0) {
        this.loading = true;
        let str = '';
        this.selectedRows.map(x => {
          if(x.jfStatus === 55651001) {
            str += x.jfCode + ',';
         }
        });
        console.log(str);
        // const res = await piliangDown({ids: str});
        const res = await batchUpdateJf({jfCode: str, jfStatus: 55651002});
        this.fetchParams = {...this.fetchParams};
        this.loading = false;
      } else {
        this.loading = false;
        return this.$notify.warning({title: '提示信息', message: '请勾选后再进行启用！'});
      }
    },

    //批量启用
    async batchBack() {
      if (this.selectedRows.length > 0) {
        this.loading = true;
        let str = '';
        this.selectedRows.map(x => {
          if(x.dataSource == '55641001'){
          str += x.urgentId + ',';
          }
        });
        console.log(str);
        const res = await piliangBack({ids: str});
        this.fetchParams = {...this.fetchParams};
        this.loading = false;
      } else {
        this.loading = false;
        return this.$notify.warning({title: '提示信息', message: '请勾选后再进行启用！'});
      }
    },
    resetHandle(val){
      console.log("reset")
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams.ownerCode = null;
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
    },
  }
  // mounted() {
  //   this.BaseTable = this.$refs.listModal.$refs.pageTable;
  // }
};
</script>

<style lang="less" scoped></style>
